package cn.swust.designpatternlearningplatform.domain.vo;

import cn.swust.designpatternlearningplatform.common.exception.CustomException;
import cn.swust.designpatternlearningplatform.domain.entity.Topic;
import cn.swust.designpatternlearningplatform.domain.enums.TopicTypeEnum;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用于表格读取数据
 *
 * @author Tang
 * @date 2023/5/25 12:29
 **/
@Setter
@ToString
public class TopicExcelVo {
    @ExcelProperty("type")
    private String type;
    @ExcelProperty("content")
    private String content;
    @ExcelProperty("answer")
    private String answer;
    @ExcelProperty("analysis")
    private String analysis;

    /**
     * 将TopicExcelVo对象转换为TopicVo对象
     *
     * @return cn.swust.designpatternlearningplatform.domain.vo.TopicVo
     * @author Tang
     * @date 2023/5/25 12:38
     **/
    public TopicVo parse() {
        TopicVo topicVo = new TopicVo();
        //解析题干
        topicVo.setTopicContent(parseContent());
        //解析选项
        topicVo.setTopicOptionVos(parseOptions());
        //题目类型
        topicVo.setTopicType(TopicTypeEnum.topicTypeId(type));
        topicVo.setTopicAnswer(answer);
        topicVo.setTopicAnalyse(analysis);
        return topicVo;
    }

    /**
     * 解析题干
     *
     * @return java.lang.String
     * @author Tang
     * @date 2023/5/25 12:49
     **/
    private String parseContent() {
        // 定义正则表达式
        String stemRegex = "\\A(.+?)$";
        // 编译正则表达式
        Pattern stemPattern = Pattern.compile(stemRegex, Pattern.MULTILINE);
        // 匹配内容并提取题目和选项
        Matcher stemMatcher = stemPattern.matcher(content);
        if (!stemMatcher.find()) {
            throw new CustomException("题目解析失败");
        }
        return stemMatcher.group(1).trim();
    }

    /**
     * 解析选项
     *
     * @return void
     * @author Tang
     * @date 2023/5/25 12:47
     **/
    private List<TopicOptionVo> parseOptions() {
        String optionsRegex = "([A-Za-z]\\.|[一二三四五六七八九十]{1,2}、)(.+?)(?=[A-Za-z]\\.|[一二三四五六七八九十]{1,2}、|\\z)";
        Pattern optionsPattern = Pattern.compile(optionsRegex, Pattern.DOTALL);
        Matcher optionsMatcher = optionsPattern.matcher(content);

        int i = 0;
        char pre = 'A';
        List<TopicOptionVo> topicOptionVos = new ArrayList<>();
        while (optionsMatcher.find()) {
            TopicOptionVo topicOptionVo = new TopicOptionVo();
            topicOptionVo.setOptionName(String.valueOf((char) (pre + (i++))));
            topicOptionVo.setOptionContent(optionsMatcher.group(2).trim());
            topicOptionVos.add(topicOptionVo);
        }
        return topicOptionVos;
    }
}
